<!--
 * @Author: 胡俊/treence
 * @Date: 2022-05-24 09:45:03
 * @LastEditors: 黄宇/Hyuishine
 * @LastEditTime: 2024-05-14 16:32:04
 * @Description: 
 * @Email: treence@gmail.com
 * @Company: 3xData
 * @youWant: 我的=》工作场所=》表单
-->
  <template >
  <view class="container_page">

    <!-- 顶部自定义导航栏 -->
    <action-bar :options="navOptions" />
    <view class="main">
      <view class="card">
        <view class="title">工作场所信息</view>

        <view class="formItem">
          <view class="label">场地名称</view>
          <input class="content"
                 v-model="formObject.name"
                 placeholder="请输入场地名称" />
        </view>

        <view class="formItem">
          <view class="label">工作场所地址</view>
          <input class="content"
                 v-model="formObject.address"
                 placeholder="请输入工作场所地址" />
        </view>

        <view class="formItem">
          <view class="label">建筑面积</view>
          <input class="content"
                 type="number"
                 v-model="formObject.areaSize"
                 placeholder="请输入建筑面积" />
        </view>
      </view>
      <view class="card">
        <view class="title">产权证明或租赁合同(原件)
          <view class="titleTip">（产权证明或租赁合同需逐页扫描或拍照上传）</view>
        </view>
        <!-- <upload-img v-if="formObject.securitiesFiles != ''"
                    :imgList="formObject.securitiesImgs"
                    :imgcount="1"
                    ></upload-img>
        <div v-else> -->
        <template>
          <!-- :value="listSelected" -->
          <!-- <uni-file-picker fileMediatype="all"
                           ref="imageValues"
                           :value="listSelected"
                           mode="grid"
                           :limit="1"
                           @select="select($event)"
                           @progress="progress"
                           @success="success"
                           @fail="fail" /> -->
          <uni-file-picker :value="listSelected"
                           @select="select($event)"
                           mode="grid"
                           :limit="1"
                           file-mediatype="all">
          </uni-file-picker>
        </template>
        <!-- </div> -->
      </view>

      <!-- <view class="card">
        <view class="title">产权证明或租赁合同图片
        </view>
        <upload-img :imgList="formObject.securitiesImgs"
                    :imgcount="1"
                    @changeImage="uploadSuccess($event,'securitiesImgs')"></upload-img>
      </view> -->

      <view class="allBtn">
        <view class="btn"
              @click="save">
          <view>保存</view>
        </view>
        <view class="btn1"
              v-if="siteId"
              @click="delImg">
          <view>删除</view>
        </view>
      </view>
    </view>

    <toast></toast>
  </view>
</template>
<script>
import { baseImgUrl, baseApiUrl } from '@/config.js';
import UploadImg from '@/components/upload/upload-img.vue';
export default {
  components: { UploadImg },
  data () {
    return {
      imageValue: [],
      navOptions: {
        // 导航栏配置参数
        statusBar: "dark",
        left: {
          icon: "back",
        },
        center: {
          title: "工作场所",
        },
      },
      siteId: '',// 表单id
      baseImgUrl: baseImgUrl,
      baseImgUrl: baseImgUrl,

      formObject: {
        address: '', // 工作场所地址
        areaSize: '', // 建筑面积
        name: '',// 场地名称
        securitiesFiles: '', // 产权证明或租赁合同
        // securitiesImgs: '' // 产权证明或租赁合同图片
      },
      form: {
        address: '', // 工作场所地址
        areaSize: '', // 建筑面积
        name: '',// 场地名称
        securitiesFiles: '', // 产权证明或租赁合同
        // securitiesImgs: '' // 产权证明或租赁合同图片
      },
      listSelected: [],
      imgPath: '/common/upload',
      loading: false,
    }
  },
  onLoad (options) {
    // 获取表单id
    if (options.id) {
      this.siteId = options.id
      this.getForm()
    }
  },
  methods: {
    // 获取表单信息
    getForm () {
      if (this.loading) return

      this.loading = true
      uni.showLoading({
        title: '正在加载请稍后',
        mask: true
      });

      this.$store.dispatch('site_form', this.siteId)
        .then(res => {
          if (res && res.code === 200) {
            this.formObject = res.data
            // 将文件路径转化成数组格式
            if (res.data.securitiesFiles) {
              let listSelected = res.data.securitiesFiles.split(',')
              listSelected.forEach(item => {
                let name = item.split('/').slice(-1)[0]
                let data = {
                  url: baseImgUrl + item,
                  name: name
                }
                this.listSelected.push(data)
              })
            }
          }
        })
        .finally(() => {
          let timer = setTimeout(() => {
            this.loading = false
            uni.hideLoading();
            clearTimeout(timer)
          }, 3000);
        })
    },
    // 保存
    save () {
      if (this.loading) return

      this.loading = true
      uni.showLoading({
        title: '正在加载请稍后',
        mask: true
      });
      // 校验
      if (this.validateForm()) {
        // 将文件路径转化成字符串格式
        // if (this.formObject.securitiesImgs instanceof Array) {
        //   this.formObject.securitiesImgs = this.formObject.securitiesImgs.join(',')
        // }
        // 修改
        if (this.siteId) {
          this.$store.dispatch('site_update', this.formObject)
            .then(res => {
              if (res && res.code === 200) {
                this.$showToast({
                  show: true,
                  text: '修改成功!'
                })
                setTimeout(() => {
                  uni.navigateBack()
                }, 1000)
              } else {
                this.$showToast({
                  show: true,
                  text: res.msg
                })
              }
            })
            .finally(() => {
              let timer = setTimeout(() => {
                this.loading = false
                uni.hideLoading();
                clearTimeout(timer)
              }, 3000);
            })
        } else { // 新增
          this.$store.dispatch('site_add', this.formObject)
            .then(res => {
              if (res && res.code === 200) {
                this.$showToast({
                  show: true,
                  text: '新增成功!'
                })
                setTimeout(() => {
                  uni.navigateBack()
                }, 1000)
              } else {
                this.$showToast({
                  show: true,
                  text: res.msg
                })
              }
            })
            .finally(() => {
              let timer = setTimeout(() => {
                this.loading = false
                uni.hideLoading();
                clearTimeout(timer)
              }, 3000);
            })
        }
      } else {
        this.$showToast({
          show: true,
          text: '信息未填写完整！'
        })
      }
    },
    // 删除
    delImg () {
      uni.showModal({
        title: '提示',
        content: '确定要删除该工作场所？',
        cancelText: '取消',
        confirmText: '确认',
        success: res => {
          if (res.confirm) {
            this.loading = true
            uni.showLoading({
              title: '正在删除请稍后',
              mask: true
            });
            this.$store.dispatch('site_remove', this.siteId)
              .then(res => {
                if (res && res.code === 200) {
                  this.$showToast({
                    show: true,
                    text: '删除成功!'
                  })
                  setTimeout(() => {
                    uni.navigateBack()
                  }, 1000)
                } else {
                  this.$showToast({
                    show: true,
                    text: res.msg
                  })
                }
              })
              .finally(() => {
                let timer = setTimeout(() => {
                  this.loading = false
                  uni.hideLoading();
                  clearTimeout(timer)
                }, 3000);
              })
          }
        }
      });
    },
    // 上传成功回调函数
    uploadSuccess (e, label) {
      this.formObject[label] = e.join(',')
    },

    // 获取上传状态
    select (e, index, key) {
      let size = e.tempFiles[0].size
      if (size <= 1024 * 1024 * 20) {
        this.loading = true
        uni.showLoading({
          title: '正在上传请稍后',
          mask: true
        });
        uni.uploadFile({
          url: baseApiUrl + this.imgPath, //仅为示例，非真实的接口地址
          filePath: e.tempFilePaths[0],
          name: 'file',
          formData: {
            'user': 'test'
          },
          success: (uploadFileRes) => {
            let dist = JSON.parse(uploadFileRes.data)
            if (dist.code != 200) {
              uni.showToast({
                title: '上传失败',
                icon: "none",
                duration: 2000
              })
            } else {
              this.$set(this.formObject, 'securitiesFiles', dist.fileName)
            }
          },
          complete: () => {
            let timer = setTimeout(() => {
              this.loading = false
              uni.hideLoading();
              clearTimeout(timer)
            }, 3000);
          }
        });
      } else {
        this.$refs.imageValues[0].clearFiles()
        uni.showToast({
          title: '文件过大',
          icon: "none",
          duration: 2000
        })

      }

    },
    // 获取上传进度
    progress (e) {
      console.log("上传进度：", e);
    },

    // 上传成功
    success (e) {
      console.log("上传成功");
    },

    // 上传失败
    fail (e) {
      console.log("上传失败：", e);
    },
    //! 提供给父组件的校验方法，错误时返回表单名
    validateForm () {
      let result = true
      for (const item in this.formObject) {
        for (const key in this.form) {
          if (item == key && !this.formObject[item]) {
            console.log(item, this.formObject[item])
            result = false
            break
          }
        }

        if (result == false) {
          break
        }
      }
      return result
    },

  }
}
</script>
<style lang="less">
.container_page {
  background: #f4f5f5;
  height: 100vh;
  font-size: 28rpx;
}
.main {
  height: 100vh;
  overflow: auto;
  padding-bottom: 300rpx;
  .card {
    background: white;
    margin-bottom: 16rpx;
    padding: 40rpx 24rpx;
    border-radius: 20rpx;

    & > view:not(:last-child) {
      margin-bottom: 20rpx;
    }
  }
}
.title {
  color: #333;
  font-size: 30rpx;
  font-weight: bold;
  line-height: 36rpx;
  .titleTip {
    display: inline;
    font-weight: 300;
    font-size: 20rpx;
    color: red;
  }
}
.formItem {
  display: flex;
  align-items: center;

  .label {
    color: #333;
    font-size: 28rpx;
    font-weight: 400;
    line-height: 36rpx;
    width: 35%;
  }

  .content {
    flex: 1;
    text-align: right;
  }
}

.allBtn {
  bottom: 50rpx;
  .btn {
    width: 100%;
    bottom: 25rpx;
    left: 0;
    & > view {
      height: 80rpx;
      border-radius: 10rpx;
      background: #5390ff;
      margin: 0 24rpx;
      text-align: center;
      line-height: 80rpx;
      font-size: 32rpx;
      color: #ffffff;
    }
  }
  .btn1 {
    margin-top: 25rpx;
    width: 100%;
    left: 0;
    & > view {
      height: 80rpx;
      border-radius: 10rpx;
      background: #ff4539;
      margin: 0 24rpx;
      text-align: center;
      line-height: 80rpx;
      font-size: 32rpx;
      color: #ffffff;
    }
  }
}
</style>